<template>
  <div class="app-container" style="height: 100%; padding-bottom: 0">
    <el-tabs v-model="currTab" type="card" class="tab-box" :class="{ disabled: disableAction }">
      <el-tab-pane label="关键工序" name="table" />
      <el-tab-pane label="安全文明" name="sc" />
      <el-tab-pane label="抽检流程" name="course" />
      <el-tab-pane label="交付" name="GC-001-004" />
      <el-tab-pane label="售后" name="GC-001-005" />
      <el-tab-pane label="展示区" name="GC-001-006" />
    </el-tabs>
    <el-container style="height: calc(100% - 56px)">
      <el-aside width="300px" style="background-color: #fff; margin: 0; padding: 0">
        <el-select v-model="currTypeId" size="mini" placeholder="请选择阶段" :loading="checkTypeLoading" clearable filterable style="width: 100%" v-if="currTab === 'table'">
          <el-option v-for="item in checkTypeList" :key="item.typeId" :label="item.typeName" :value="item.typeId" :title="item.typeName" style="max-width: 500px" />
        </el-select>
        <el-input v-model="currTableName" :placeholder="'请输入' + showTableName" clearable size="mini" prefix-icon="el-icon-search" style="margin-bottom: 20px" />
        <div ref="leftBar" style="height: calc(100% - 90px); overflow: auto" v-loading="checkTableLoading">
          <el-tree class="tree-box" ref="tree" :data="checkTableList" :props="{ label: 'tableName' }" node-key="tableId" highlight-current :filter-node-method="filterNode" default-expand-all @node-click="handleNodeClick">
            <div class="el-tree-node__label" slot-scope="{ node, data }">
              <el-tag type="info" class="sc-tag" size="mini" v-if="data.specialTypeId" :style="{ color: displaySpecialType('color', data.specialTypeId) }">
                {{ data.specialTypeId | selectEnumLabel(specialTypes) }}
              </el-tag>
              <el-tag type="info" class="sc-tag" size="mini" v-if="isSc && data.scType" :style="{ color: displayScType('color', data.scType) }" :title="displayScType('label', data.scType)">
                {{ displayScType('abbr', data.scType) }}
              </el-tag>
              <el-tag type="info" class="sc-tag" size="mini" v-if="isCategory && data.chkitemName">{{ data.chkitemName }}</el-tag>
              <span :title="node.label">{{ node.label }}</span>
            </div>
          </el-tree>
        </div>
      </el-aside>
      <el-main style="padding: 0 0 0 20px">
        <el-form ref="queryForm" :model="queryParams" size="mini" inline style="white-space: nowrap; overflow-x: auto" :class="{ disabled: disableAction }" @submit.native.prevent>
          <el-form-item prop="content">
            <el-input v-model.trim="queryParams.content" placeholder="请输入验收标准内容" clearable />
          </el-form-item>
          <el-form-item prop="seriousLevel">
            <el-select v-model="queryParams.seriousLevel" placeholder="严重等级" clearable style="width: 120px">
              <el-option v-for="dict in dict.type.sys_standard_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item prop="modules">
            <el-select v-model="queryParams.modules" placeholder="模块" clearable style="width: 120px">
              <el-option v-for="dict in dict.type.cq_data_modules" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item prop="blocks">
            <el-select v-model="queryParams.blocks" placeholder="分块" clearable style="width: 120px">
              <el-option v-for="dict in dict.type.cq_data_blocks" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item prop="rdcCourses">
            <el-select v-model="queryParams.rdcCourses" placeholder="过程分类" clearable style="width: 120px">
              <el-option v-for="dict in dict.type.cq_process_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button size="mini" icon="el-icon-refresh" :disabled="loading" @click="resetQuery">重置</el-button>

            <el-button size="mini" type="primary" icon="el-icon-plus" :disabled="loading" @click="openEditItem({ [idField]: currTableId })" v-hasPermi="['cq:checkStandard:add']" v-if="currTableId">新增</el-button>
            <el-popover placement="top" trigger="hover" :content="'请选择左侧' + showTableName" v-else>
              <el-button slot="reference" size="mini" type="primary" icon="el-icon-plus" v-hasPermi="['cq:checkStandard:add']" style="margin-left: 10px">新增</el-button>
            </el-popover>
          </el-form-item>
        </el-form>

        <el-table
          class="standards-table"
          v-loading="loading"
          :data="filteredList"
          size="small"
          highlight-current-row
          :height="showCheckMrq ? 'calc((100% - 70px) * 0.5)' : 'calc(100% - 50px)'"
          style="min-height: 200px"
          @current-change="handleCurrentChange"
        >
          <el-table-column label="序号" type="index" width="50" />
          <el-table-column label="验收标准" prop="content" show-overflow-tooltip min-width="300">
            <span slot-scope="{ row }" :style="{ color: ['2', '3'].includes(row.seriousLevel) ? 'red' : '' }">{{ row.seriousLevel == '3' ? '*' : '' }} {{ row.content }}</span>
          </el-table-column>
          <el-table-column label="模块" align="center" show-overflow-tooltip>
            <dict-tag slot-scope="{ row }" :options="dict.type.cq_data_modules" :value="row.modules" />
          </el-table-column>
          <el-table-column label="分块" align="center" show-overflow-tooltip width="100">
            <dict-tag slot-scope="{ row }" :options="dict.type.cq_data_blocks" :value="row.blocks" />
          </el-table-column>
          <el-table-column label="部位" align="center" show-overflow-tooltip>
            <dict-tag slot-scope="{ row }" :options="dict.type.cq_data_positions" :value="row.positions" />
          </el-table-column>
          <el-table-column label="数据归集" align="center" show-overflow-tooltip>
            <dict-tag slot-scope="{ row }" :options="dict.type.cq_data_collections" :value="row.dataCollections" />
          </el-table-column>
          <el-table-column label="质量分类" align="center" show-overflow-tooltip>
            <dict-tag slot-scope="{ row }" :options="dict.type.cq_location_type" :value="row.locationType" />
          </el-table-column>
          <el-table-column label="过程分类" align="center" show-overflow-tooltip min-width="100">
            <span slot-scope="{ row }">{{ row.rdcCourses | processTypeFilter(dict.label.cq_process_type) }}</span>
          </el-table-column>
          <el-table-column label="是否启用" align="center" min-width="80">
            <el-tag slot-scope="{ row }" size="small" :type="row.isEnable ? 'primary' : 'info'">{{ row.isEnable ? '启用' : '禁用' }}</el-tag>
          </el-table-column>
          <el-table-column label="排序" prop="seq" align="center" width="50" />
          <el-table-column label="操作" align="center" width="120">
            <template slot-scope="{ row }">
              <el-button size="mini" type="text" icon="el-icon-edit" @click.stop="openEditItem(row)" v-hasPermi="['cq:checkStandard:edit']">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" :loading="row.removeLoading" @click.stop="btnRemoveItem(row)" v-hasPermi="['cq:checkStandard:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <CheckMrqList ref="CheckMrqList" />
      </el-main>
      <EditStandard ref="EditStandard" v-model="showEditStandard" @ok="getList" />
    </el-container>
  </div>
</template>
<script>
// 工程质量-验收标准页面
// import { getFirstLeaf } from '@/utils'
import { debounce, flatList2tree, removeEmptyArray, isLikeOrEqual } from '@/utils'
import { specialTypeList, cqCheckScTypes } from '@/utils/baseData'
import { getSpecialTypes } from '@/utils/dict/custom'
import { listCheckType, listCheckTable, listCheckSc, listRdcCourse, listCheckStandard, delCheckStandard } from '@/api/qualityManage/cq'
import { getCategory } from '@/api/checkScore/cqEval'
import EditStandard from './components/EditCheckStandard'
import CheckMrqList from './components/CheckMrqList'

const specialType2obj = specialTypeList.reduce((o, i) => !void (o[i.value] = i) && o, {})
const displaySpecialType = (key, value) => (specialType2obj[value] || {})[key]

const scType2obj = cqCheckScTypes.reduce((o, i) => !void (o[i.value] = i) && o, {})
const displayScType = (key, value) => (scType2obj[value] || {})[key]

export default {
  name: 'CheckStandard',
  components: { EditStandard, CheckMrqList },
  dicts: ['sys_standard_type', 'cq_data_modules', 'cq_data_blocks', 'cq_data_positions', 'cq_data_collections', 'cq_process_type', 'cq_location_type'],
  filters: {
    processTypeFilter(val, value2label = {}) {
      const str = val || ''
      return str
        .split(',')
        .map(i => value2label[i])
        .filter(i => i)
        .join('，')
    }
  },
  data() {
    return {
      displaySpecialType,
      displayScType,
      currTab: 'table', // table 工序, sc 安全文明, course 抽检流程
      checkTypeList: [], // 阶段
      checkTableList: [], // 工序
      checkTableRaw: [], // 工序原数据
      checkTypeLoading: false,
      checkTableLoading: false,
      currTypeId: '', // 当前选中阶段ID
      currTableId: '', // 当前选中工序ID
      currTableName: '',
      queryParams: {
        content: '',
        seriousLevel: '',
        rdcCourses: '',
        modules: '',
        blocks: ''
      },
      loading: false,
      list: [],
      filteredList: [],
      showEditStandard: false,
      showCheckMrq: false, // 显示实测实量列表
      specialTypes: [] // 专业类别
    }
  },
  computed: {
    disableAction() {
      return this.checkTypeLoading || this.checkTableLoading || this.loading
    },
    isSc() {
      return this.currTab === 'sc'
    },
    isCourse() {
      return this.currTab === 'course'
    },
    isCategory() {
      return this.currTab.startsWith('GC-001')
    },
    showTableName() {
      return this.isCategory ? '分类名称' : this.isCourse ? '抽检流程' : '工序名称'
    },
    idField() {
      return this.isCategory ? 'evalCategoryId' : this.isCourse ? 'courseId' : this.isSc ? 'scId' : 'tableId'
    },
    listApi() {
      return this.isCategory ? getCategory : this.isCourse ? listRdcCourse : this.isSc ? listCheckSc : listCheckTable
    },
    paramOfListAll() {
      return this.isCourse ? 0 : 'all'
    }
  },
  watch: {
    currTab(val) {
      this.resetQuery()
      this.getCheckTableList()
    },
    currTypeId(val) {
      this.$refs.tree.filter(this.currTableName)
    },
    currTableName(val) {
      this.$refs.tree.filter(val)
    },
    queryParams: {
      deep: true,
      handler() {
        this.handleQueryDebounce()
      }
    }
  },
  created() {
    this.handleQueryDebounce = debounce(this.handleQuery)
    this.btnRemoveItem = debounce(this.removeItem, 1e3, true)
    getSpecialTypes().then(res => (this.specialTypes = res))
    this.getCheckTypeList()
    this.getCheckTableList()
    this.getList()
  },
  methods: {
    filterNode(value, data) {
      return isLikeOrEqual(data, { like: { tableName: value }, eq: { typeId: this.currTypeId } })
    },
    handleNodeClick(data) {
      if (!data.isLeaf) {
        // 解决当前项高亮丢失
        this.$nextTick(() => this.$refs.tree?.setCurrentKey(this.currTableId))
        return
      }
      if (data.tableId === this.currTableId) return
      this.currTableId = data.tableId
      this.getList()
    },
    async getCheckTypeList() {
      this.checkTypeLoading = true
      const res = await listCheckType({ isEnable: true }).catch(() => false)
      this.checkTypeLoading = false
      // if (res === false) return
      const data = res?.data || []
      this.checkTypeList = data
      // this.currTypeId = data[0]?.typeId || ''
    },
    async getCheckTableList() {
      let opt = { isEnable: true }
      if (this.isCategory) opt = { chkitemType: this.currTab }

      this.checkTableLoading = true
      const res = await this.listApi(opt).catch(() => false)
      this.checkTableLoading = false
      if (res === false) return (this.checkTableList = [])

      let data = res.data || []
      this.checkTableRaw = JSON.parse(JSON.stringify(data))

      // 让安全文明或抽检流程拥有工序对应字段
      if (this.isSc) {
        data.map(i => {
          i.tableId = i.scId
          i.tableName = i.scName
        })
      }
      if (this.isCourse) {
        data.map(i => {
          i.tableId = i.courseId
          i.tableName = i.courseName
          // 抽检流程每层都可编辑，每项当叶子处理
          i.isLeaf = true
        })
      }
      if (this.isCategory) {
        data.map(i => {
          i.tableId = i.evalCategoryId
          i.tableName = i.evalCategoryName
        })
      }

      data = flatList2tree(data, { id: 'tableId', parent: 'parentId' })
      data = removeEmptyArray(data)
      this.checkTableList = data

      // 获取第一个工序子级
      // const res2 = getFirstLeaf(data)
      // this.currTableId = res2.tableId
      // this.$nextTick(() => this.$refs.tree?.setCurrentKey(res2.tableId))

      // 滚动到顶部
      const leftBar = this.$refs.leftBar
      if (leftBar) leftBar.scrollTop = 0
    },
    async getList() {
      const opt = {
        [this.idField]: this.currTableId || this.paramOfListAll
      }
      if (this.isCategory) opt.chkitemType = this.currTab

      this.loading = true
      const res = await listCheckStandard(opt).catch(() => false)
      this.loading = false
      if (res === false) {
        this.list = []
        this.filteredList = []
        return
      }

      const data = res.data || []
      data.map(i => (i.removeLoading = false))
      this.list = data
      this.handleQuery()
    },
    handleQuery() {
      // 本地过滤
      const { content, seriousLevel, rdcCourses, modules, blocks } = this.queryParams
      const opts = { like: { content, rdcCourses }, eq: { seriousLevel, modules, blocks } }
      this.filteredList = this.list.filter(i => isLikeOrEqual(i, opts))
    },
    resetQuery() {
      this.currTypeId = ''
      this.currTableId = ''
      this.currTableName = ''
      this.resetForm('queryForm')
      this.getList()
      this.$nextTick(() => this.$refs.tree.setCurrentKey())
    },
    handleCurrentChange(item) {
      // 只有分块为实测实量时可启用
      const showCheckMrq = item?.blocks === 'zl-scsl' && item?.standardId
      this.showCheckMrq = showCheckMrq
      showCheckMrq ? this.$refs.CheckMrqList?.open({ standardId: item.standardId }) : this.$refs.CheckMrqList?.reset()
    },
    async removeItem(item) {
      if (item.removeLoading) return
      const res1 = await this.$confirm(`确认删除数据项：${item.content}?`, '警告', { type: 'warning' }).catch(() => false)
      if (res1 !== 'confirm') return

      item.removeLoading = true
      const res = await delCheckStandard(item.standardId).catch(() => false)
      item.removeLoading = false
      if (res === false) return

      this.msgSuccess('删除成功')
      this.getList()
    },
    openEditItem(item = {}) {
      if (this.isCategory) item.chkitemType = this.currTab
      this.$refs.EditStandard.open(item, this.checkTableRaw)
    }
  }
}
</script>
<style lang="scss" scoped>
.tab-box {
  /deep/ .el-tabs__item {
    font-size: 12px;
  }
}
.tree-box {
  /deep/ .el-tree-node__children {
    overflow: unset;
  }
  .sc-tag {
    zoom: 0.9;
    margin-right: 5px;
    padding: 0 4px;
  }
}
.standards-table::before {
  content: none;
}
</style>
